package lox

class LoxClass(
    internal val name: String, private val superclass: LoxClass?, private val methods: Map<String, LoxFunction>
) : LoxCallable {
    override fun call(interpreter: Interpreter, arguments: List<Any?>): Any? =
        LoxInstance(this).also { findMethod("init")?.bind(it)?.call(interpreter, arguments) }

    override fun arity(): Int = when (val initializer = findMethod("init")) {
        null -> 0
        else -> initializer.arity()
    }

    override fun toString(): String = name

    fun findMethod(name: String): LoxFunction? = when (val res = methods[name]) {
        null -> superclass?.findMethod(name)
        else -> res
    }

}
